package com.yk.silence.rxmvp.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.yk.silence.rxmvp.util.ToastUtils;

public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView {

    public Context mContext;
    private ProgressDialog mDialog;
    protected P mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(getLayoutId());
        if (mPresenter == null) {
            mPresenter = createPresenter();
        }
        initView();
        initData();

    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void showLoadingFileDialog() {
        mDialog = new ProgressDialog(mContext);
        mDialog.setMessage("正在下载中,请稍后");
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setMax(100);
        mDialog.show();
    }

    @Override
    public void hideLoadingFileDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onProgress(long totalSize, long downSize) {
        if (mDialog != null) {
            mDialog.setProgress((int) (downSize * 100 / totalSize));
        }
    }

    @Override
    public void hideLoading() {
        closeLoadingDialog();
    }

    @Override
    public void showError(String msg) {
        ToastUtils.getInstance().shortToast(mContext, msg);
    }

    @Override
    public void onErrorCode(BaseModel model) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter = null;
        }
        ToastUtils.getInstance().onDestroy();
    }

    /**
     * 创建
     *
     * @return
     */
    protected abstract P createPresenter();

    /**
     * 获取layout
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 隐藏下载文件对话框
     */
    public void hideFileDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    /**
     * 关闭对话框
     */
    private void closeLoadingDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    /**
     * 显示对话框
     */
    private void showLoadingDialog() {

        if (mDialog == null) {
            mDialog = new ProgressDialog(mContext);
        }
        mDialog.setCancelable(false);
        mDialog.show();
    }
}
